/**
 * User: alesj
 * Date: 2004.8.25
 * Time: 10:01:13
 */

package com.generalynx.ecos.utils;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

public class SettingsFactoryBean implements FactoryBean, InitializingBean {

    protected final Log logger = LogFactory.getLog(getClass());
    private Settings m_settings;

    private Resource m_config;
    private Properties m_properties;

    public Resource getConfig() {
        return m_config;
    }

    public void setConfig(Resource config) {
        m_config = config;
    }

    public Properties getProperties() {
        return m_properties;
    }

    public void setProperties(Properties properties) {
        m_properties = properties;
    }

    public void afterPropertiesSet() throws Exception {
        Properties props = new Properties();

        if (getConfig() != null) {
            // load properties from given location
            InputStream is = getConfig().getInputStream();
            try {
                props.load(is);
            } finally {
                is.close();
            }
        }

        if (getProperties() != null) {
            for (Enumeration enums = getProperties().propertyNames(); enums.hasMoreElements();) {
                String key = (String)enums.nextElement();
                props.setProperty(key, getProperties().getProperty(key));
            }
        }

        logger.info("Settings properties initialized.");
        m_settings = new Settings(props);
    }

    public Object getObject() throws Exception {
        return m_settings;
    }

    public Class getObjectType() {
        return Settings.class;
    }

    public boolean isSingleton() {
        return true;
    }
}
